package com.zhdl.hardware_contact.hardware_web.service;

import com.zhdl.common.ytools.callback.CommonCallback;
import com.zhdl.hardware_contact.hardware_config.entity.ProjectConfiguration;
import com.zhdl.hardware_contact.hardware_config.entity.ProjectParameter;
import com.zhdl.hardware_contact.hardware_config.service.ProjectConfigService;
import com.zhdl.hardware_contact.hardware_config.service.ProjectParamService;
import com.zhdl.hardware_contact.hardware_config.service.dto.ProjectConfigQueryCriteria;
import com.zhdl.hardware_contact.hardware_param.entity.*;
import com.zhdl.hardware_contact.hardware_param.service.*;
import com.zhdl.hardware_contact.hardware_param.service.dto.HardwareActionMiddleQueryCriteria;
import com.zhdl.hardware_contact.hardware_param.service.dto.ProjectActionDictQueryCriteria;
import com.zhdl.hardware_contact.hardware_web.respone.*;
import com.zhdl.modules.process.service.ProjectConfigProcessService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Data
public class HardwareCurrentService {

    @Resource
    private HardwareDictionaryService hardwareDictionaryService;
    @Resource
    private ProjectConfigService projectConfigService;

    @Resource
    private HardwareActionMiddleService hardwareActionMiddleService;
    @Resource
    private HardwareActionParamDictService hardwareActionParamDictService;
    @Resource
    private HardwareActionDictService hardwareActionDictService;
    @Resource
    private ProjectParamService projectParamService;
    @Resource
    private ProjectActionDictService projectActionDictService;


    Map<Integer,String> HardwareErrcodeMap = new HashMap<>();

    static  Map<Integer, List<HardwareConfigResp>> HardwareCurrentAddressMap = new HashMap<>();
    //硬件实时信息Map
    static Map<Integer, List<ProjectConfiguration>> HardwareCurrentAddressMessageMap = new HashMap<>();

    //IO实时信息列表
    static List<HardwareConfigResp> HardwareConfigCurrentMsg = new ArrayList<>();



    //初始化 HardwareCurrentAddressMessageMap,HardwareConfigCurrentMsg
    public void initHardwareCurrent(){
        initHardwareCurrentAddressMessageMap();
        initHardwareConfigCurrentMsg();
    }

    //更新实时信息
    public void updateHardwareCurrent(){
        updateHardwareCurrentAddressMessageMap();
        updateHardwareConfigCurrentMsg();
    }

    public void initHardwareCurrentAddressMessageMap(){
        HardwareCurrentAddressMessageMap.clear();

        HardwareCurrentAddressMap.clear();

        ProjectConfigQueryCriteria projectConfigQueryCriteria;
        List<HardwareDictionary> hardwareDictionaries = hardwareDictionaryService.selectAll();

        for (HardwareDictionary hardwareDictionary : hardwareDictionaries) {


            //查询硬件的动作列表,获取errCode的Field
            HardwareDictionary hardwareDictById = hardwareDictionaryService.selectById(hardwareDictionary.getId());
            List<Integer> hardwareIds = insertList(hardwareDictById.getId());
            HardwareActionMiddleQueryCriteria queryCriteria = new HardwareActionMiddleQueryCriteria();
            queryCriteria.setHardwareId(hardwareIds);
            List<HardwareActionMiddle> actionMiddles = hardwareActionMiddleService.findList(queryCriteria);
            if (!actionMiddles.isEmpty()) {
                List<HardwareInfoActionConfigResp> actionParamResults = new ArrayList<>();
                actionMiddles.forEach(actionMiddle -> {
                    HardwareActionParamDict hardwareActionParamDict = hardwareActionParamDictService.selectById(actionMiddle.getParamId());
                    if (hardwareActionParamDict != null) {
                        HardwareInfoActionConfigResp actionParamResult = new HardwareInfoActionConfigResp();
                        BeanUtils.copyProperties(hardwareActionParamDict, actionParamResult);
                        HardwareActionDict hardwareActionDict = hardwareActionDictService.selectById(hardwareActionParamDict.getActionId());
                        if (hardwareActionDict != null) {
                            actionParamResult.setActionDict(hardwareActionDict);
                        }
                        ProjectConfiguration projectConfiguration = projectConfigService.selectById(hardwareActionParamDict.getAddressId());
                        if (projectConfiguration != null) {
                            actionParamResult.setProjectConfiguration(projectConfiguration);
                        }

                        List<ProjectParameter> ProjectParameterList = new ArrayList<>();
                        if (!Objects.equals(hardwareActionParamDict.getParamId(), "-999")) {
                            String[] paramId = hardwareActionParamDict.getParamId().split(",");
                            for (String s : paramId) {
                                ProjectParameter projectParameter = projectParamService.selectById(Integer.parseInt(s));
                                ProjectParameterList.add(projectParameter);
                            }
                        } else {
                            ProjectParameter projectParameter = projectParamService.selectById(Integer.parseInt(hardwareActionParamDict.getParamId()));
                            ProjectParameterList.add(projectParameter);
                        }
                        if (!ProjectParameterList.isEmpty()) {
                            actionParamResult.setProjectParameter(ProjectParameterList);
                        }
                        actionParamResults.add(actionParamResult);
                    }
                });

                List<ProjectActionConfigResp> actionResult = new ArrayList<>();
                ProjectActionDictQueryCriteria queryCriteria1 = new ProjectActionDictQueryCriteria();
                queryCriteria1.setHardwareId(hardwareIds); // 假设hardwareIds是一个已知且可用的集合
                List<ProjectActionDict> projectActionByCondition = projectActionDictService.findList(queryCriteria);

                // 使用Java 8的Stream API来简化集合处理
                for (ProjectActionDict projectActionDict : projectActionByCondition) {
                    ProjectActionConfigResp projectActionConfigResp = new ProjectActionConfigResp();
                    BeanUtils.copyProperties(projectActionDict, projectActionConfigResp);
                    // 将paramIds字符串数组转换为整数列表
                    List<Integer> paramIds = stringArrayToIntegerArray(projectActionDict.getParamIds());
                    // 使用Stream API和filter来匹配actionParamResults
                    List<HardwareInfoActionConfigResp> matchedActionParams =
                            actionParamResults.
                                    stream().filter(
                                            actionParamResult -> paramIds.contains(actionParamResult.getId())).
                                    collect(Collectors.toList());
                    // 设置匹配的actionParams到response对象
                    projectActionConfigResp.setHardwareInfoActionConfigRespList(matchedActionParams);
                    // 将处理好的response对象添加到结果列表中
                    actionResult.add(projectActionConfigResp);
                }

                for (ProjectActionConfigResp projectActionConfigResp : actionResult) {
                    if(projectActionConfigResp.getName().equals("alarm")){
                        if(!(projectActionConfigResp.getHardwareInfoActionConfigRespList().get(0).getProjectConfiguration()==null)) {
                            HardwareErrcodeMap.put(hardwareDictionary.getId(), projectActionConfigResp.getHardwareInfoActionConfigRespList().get(0).getProjectConfiguration().getField());
                        }
                    }
                }

            }






            List<Integer> ids = new ArrayList();
            projectConfigQueryCriteria = new ProjectConfigQueryCriteria();
            if (!(hardwareDictionary.getShowArray().equals("")||hardwareDictionary.getShowArray().isEmpty()||hardwareDictionary.getShowArray()==null)){
                for (String s : hardwareDictionary.getShowArray().split(",")) {
                    ids.add(Integer.parseInt(s));
                }
            }else {
                ids.add(-1);
            }
            projectConfigQueryCriteria.setId(ids);
            List<ProjectConfiguration> configTempList = projectConfigService.findList(projectConfigQueryCriteria);


            if(HardwareErrcodeMap.get(hardwareDictionary.getId())!=null) {
                for (ProjectConfiguration projectConfiguration : configTempList) {
                    if (projectConfiguration.getField().equals(HardwareErrcodeMap.get(hardwareDictionary.getId()))) {
                        projectConfiguration.setValueType(1);
                    }
                }
            }


            HardwareCurrentAddressMessageMap.put(hardwareDictionary.getId(),configTempList);
            List<HardwareConfigResp> hardwareConfigResps = new ArrayList<>();
            for (ProjectConfiguration projectConfiguration : configTempList) {
                HardwareConfigResp hardwareConfigResp = new HardwareConfigResp();
                hardwareConfigResp.setId(projectConfiguration.getId());
                hardwareConfigResp.setAddress(projectConfiguration.getAddress());
                hardwareConfigResp.setField(projectConfiguration.getField());
                hardwareConfigResp.setValue(projectConfiguration.getValue());
                hardwareConfigResp.setRemarks(projectConfiguration.getRemarks());
                hardwareConfigResp.setValueType(projectConfiguration.getValueType());
                hardwareConfigResps.add(hardwareConfigResp);
            }

            HardwareCurrentAddressMap.put(hardwareDictionary.getId(),hardwareConfigResps);







        }

        System.out.println(HardwareCurrentAddressMessageMap);
        System.out.println(HardwareCurrentAddressMap);



        updateHardwareCurrentAddressMessageMap();


    }

    public void updateHardwareCurrentAddressMessageMap(){

        HardwareCurrentAddressMessageMap.forEach((id,configurations)->{
            int i = 0;
            for (ProjectConfiguration configuration : configurations) {
                if(HardwareErrcodeMap.get(id)!=null) {
                    if (configuration.getField().equals(HardwareErrcodeMap.get(id))) {
                        if (Integer.parseInt(getProjectConfiguration(ProjectConfigProcessService.projectConfigurations, configuration).getValue()) > 0) {
                            configuration.setValue("1");
                        } else {
                            configuration.setValue("0");
                        }
                    } else {
                        configuration.setValue(getProjectConfiguration(ProjectConfigProcessService.projectConfigurations, configuration).getValue());
                    }
                }else {
                    configuration.setValue(getProjectConfiguration(ProjectConfigProcessService.projectConfigurations, configuration).getValue());
                }




                HardwareCurrentAddressMap.get(id).get(i).setValue(configuration.getValue());
                i++;
//                configuration = getProjectConfiguration(ProjectConfigProcessService.projectConfigurations , configuration);

            }
        });
    }

    //获取 projectConfigurations 中 projectConfiguration 的 value
    public ProjectConfiguration getProjectConfiguration(List<ProjectConfiguration> projectConfigurations, ProjectConfiguration projectConfiguration) {
        //判断是否条件为非空
        if (projectConfigurations == null) {
            return null;
        }
        for (ProjectConfiguration projectConfigurationTemp : projectConfigurations) {
               if (projectConfigurationTemp.getField().equals(projectConfiguration.getField()))
                   return projectConfigurationTemp;
        }
        return projectConfiguration;
    }


    public HardwareConfigResp getProjectConfiguration(List<ProjectConfiguration> projectConfigurations, HardwareConfigResp projectConfiguration) {
        //判断是否条件为非空
        if (projectConfigurations == null) {
            return null;
        }
        for (ProjectConfiguration projectConfigurationTemp : projectConfigurations) {
            if (projectConfigurationTemp.getField().equals(projectConfiguration.getField())){
                projectConfiguration.setValue(projectConfigurationTemp.getValue());
            }

        }
        return projectConfiguration;
    }




//    public List<Map> getHardwareCurrentMessage(){
//        projectConfigProcessService.setChangeCallBacks(Collections.singletonList(new CommonCallback<List<ProjectConfiguration>>() {
//            @Override
//            public void statusCallback(List<ProjectConfiguration> projectConfigurations) {
//
//
//
//            }
//        }));
//        return null;
//    }




    public void initHardwareConfigCurrentMsg(){
        HardwareConfigCurrentMsg.clear();


        List<ProjectConfiguration> projectConfigurationList = projectConfigService.getProjectConfigurationByValueType(1);
        projectConfigurationList.forEach(demo -> {
            HardwareConfigResp resp = new HardwareConfigResp();
            BeanUtils.copyProperties(demo,resp);
            HardwareConfigCurrentMsg.add(resp);
        });

        updateHardwareConfigCurrentMsg();
    }

    public void updateHardwareConfigCurrentMsg(){
        for (HardwareConfigResp projectConfiguration : HardwareConfigCurrentMsg) {
            projectConfiguration = getProjectConfiguration(ProjectConfigProcessService.projectConfigurations , projectConfiguration);
        }

    }




    public List<Integer> insertList(Integer id) {
        List<Integer> lists = new ArrayList<>();
        lists.add(id);
        return lists;
    }

    //辅助方法: 将字符串转换为 List<Inter>
    public List<Integer> stringArrayToIntegerArray(String stringArray) {
        List<Integer> ids = new ArrayList<>();
        if (stringArray.contains(",")) {
            // 去除空白字符并分割地址，然后尝试转换为整数
            ids = Arrays.stream(stringArray.split(",")).map(String::trim).filter(s -> !s.isEmpty()) // 排除空字符串
                    .map(this::tryParseInt) // 尝试将字符串转换为整数，忽略无效的
                    .filter(Objects::nonNull) // 排除转换失败的null值
                    .collect(Collectors.toList());
        } else {
            if(!(stringArray.isEmpty()||stringArray.equals("")||stringArray==null)){

                int i = Integer.parseInt(stringArray);
                ids.add(i);

            }

//            int i = Integer.parseInt(stringArray);
//            ids.add(i);
        }
        return ids;
    }

    // 辅助方法：尝试将字符串转换为整数，如果失败则返回null
    private Integer tryParseInt(String s) {
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            // 可以选择记录日志或忽略，这里选择忽略
            return null;
        }
    }


}
